package com.yyq.sos.permission;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.yyq.adms.sysmanage.pojo.SysModules;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.dao.BaseDaoImpl;


public class PermissionInterceptor extends AbstractInterceptor {
	public static List list = new ArrayList();
	
	public void init() {		
		super.init();
		List modules = new BaseDaoImpl().list(SysModules.class);
		for(int i=0; i<modules.size(); ++i){
			SysModules obj = (SysModules)modules.get(i);
			if(obj.getParentId().longValue()!=0){
				String url = obj.getModuleUrl();
				if(url.indexOf("?")>0)
					url = url.substring(0,url.indexOf("?"));
				list.add(url);
			}
		}
	}

	private static final long serialVersionUID = -7565791452709783328L;
	public static final String GOING_TO_URL_KEY = "GOING_TO";

	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext actionContext = invocation.getInvocationContext();
		HttpServletRequest req = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
		String perms = req.getSession().getServletContext().getInitParameter("permission");
		HttpSession session = req.getSession();
		if(perms!=null && perms.equalsIgnoreCase("True")){
			String cmd = req.getParameter("cmd");
			LoginUser user = (LoginUser)session.getAttribute(Constants.LOGIN_USER);
			String url = req.getRequestURI();
			if (user != null) {
				if(url.indexOf(".action")>0 && url.indexOf("login.action")<0){
					String path = url.substring(req.getContextPath().length()+1);
					if(!list.contains(path))
						return "pathError";
				}
				if(url.indexOf("services")>0)
					return invocation.invoke();
				else{
					if(url.indexOf("login.action")>0){//登陆Action
						if(cmd==null || cmd.equalsIgnoreCase(ActionType.ACTION_LOGIN))
							return "mainPage";
						if(!cmd.equalsIgnoreCase(ActionType.ACTION_LOGOUT)){//注销
							return "cmdError";
						}
					}
				}
				return invocation.invoke();
			}else{
				if(url.indexOf("login.action")>0){
					if(cmd==null)
						return "login";
					else if(cmd.equals("login")||cmd.equals("logout")){
						return invocation.invoke();
					}else{
						return "cmdError";
					}
				}
			}
			return "noUser";
		}else
			return invocation.invoke();
	}

	

}
